<template>
  <div>
    <el-select
      v-model="res"
      :multiple = "false"
      collapse-tags
      :disabled = "disabled"
      :clearable="clearablePri"
      :placeholder="placeholder"
      @visible-change = "handlerControl"
      @change = "changeValue"
      @clear="clear"
      :style="`${wd ? `width:${wd}px` : ''}`"
      class="m-2"
    >
      <el-option
        v-for="item in baseData"
        :key="item[value]"
        :label="item[label]"
        :value="item[value]">
      </el-option>
    </el-select>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, computed, watch } from 'vue'
import ElConfigProvider from 'element-plus'

export default defineComponent({
  name: 'ifSelect',
  props: {
    initRes: {
      type: String || Number
    },
    forWho: {
    },
    disabled: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: false
    },
    baseData: {
      type: Array
    },
    value: {
      type: String,
      default: 'value'
    },
    label: {
      type: String,
      default: 'label'
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    wd: {
      type: String || Number
    }
  },
  components: {
    [(ElConfigProvider as any).name]: ElConfigProvider,
  },
  setup(props, context) {
    const res = ref<Record<string, any> | unknown>()
    const isShow = ref<Boolean>(false)
    const clear = () => {
      res.value = ''
      context.emit('clearSingle', {
        forWho: props.forWho
      })
    }
    const handlerControl = (f: boolean) => {
      isShow.value = f
      if (!isShow.value) {
        context.emit('getSelectRes', {
          res: res.value,
          forWho: props.forWho
        })
      }
    }
    const changeValue = () => {
      if (isShow.value) {
        context.emit('getSelectResOnChange', {
          res: res.value as any,
          forWho: props.forWho as any
        })
      }
    }
    onMounted(() => {
      res.value = props.initRes
    })
    watch(() => props.initRes, (newVal) => {
      res.value = newVal
    })
    const clearablePri = computed(() => (props.clearable === undefined ? true : Boolean(props.clearable)))
    return {
      res,
      clearablePri,
      // methods
      clear,
      handlerControl,
      changeValue
    }
  },
})
</script>

<style scoped lang="less">
:deep(.el-menu-item-group__title){
  font-size: 20px;
  color: rgb(80, 80, 241);
}
</style>
